home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 22 / Cream of the Crop 22.iso / program / snip9611.zip / ARCCRC16.C < prev    next >
C/C++ Source or Header  |  1996-11-24  |  2KB  |  98 lines

  1. /* +++Date last modified: 02-Nov-1995 */
  2.  
  3. /*
  4. ** arccrc16.c -- calculate 16-bit CRC for file(s)
  5. ** rev. Feb. 1992
  6. ** public domain by Raymond Gardner
  7. **                  Englewood, Colorado
  8. **
  9. ** This program uses the same CRC calculation as ARC (SEA) and LHA (Yoshi)
  10. */
  11.  
  12. #include <stdio.h>
  13. #include "crc.h"
  14.  
  15. #define bufsiz (16*1024)
  16.  
  17. static WORD crc_table[256];
  18.  
  19. /*
  20. ** I determined this function empirically, by examining the
  21. ** table for patterns, and programming via trial-and-error.
  22. ** Don't ask me how it works or if it can be generalized for
  23. ** other CRC polynomials.
  24. */
  25.  
  26. void init_crc_table(void)
  27. {
  28.       int i, j;
  29.       WORD k;
  30.  
  31.       for (i = 0; i < 256; i++)
  32.       {
  33.             k = 0xC0C1;
  34.             for (j = 1; j < 256; j <<= 1)
  35.             {
  36.                   if (i & j)
  37.                         crc_table[i] ^= k;
  38.                   k = (k << 1) ^ 0x4003;
  39.             }
  40.       }
  41. }
  42.  
  43. /*
  44. ** crc_calc() -- calculate cumulative crc-16 for buffer
  45. */
  46.  
  47. WORD crc_calc(WORD crc, char *buf, unsigned nbytes)
  48. {
  49.       unsigned char *p, *lim;
  50.  
  51.       p = (unsigned char *)buf;
  52.       lim = p + nbytes;
  53.       while (p < lim)
  54.       {
  55.             crc = (crc >> 8 ) ^ crc_table[(crc & 0xFF) ^ *p++];
  56.       }
  57.       return crc;
  58. }
  59.  
  60. void do_file(char *fn)
  61. {
  62.       static char buf[bufsiz];
  63.       FILE *f;
  64.       int k;
  65.       WORD crc;
  66.  
  67.       f = fopen(fn, "rb");
  68.       if (f == NULL)
  69.       {
  70.             printf("%s: can't open file\n", fn);
  71.             return;
  72.       }
  73.       crc = 0;
  74.       while ((k = fread(buf, 1, bufsiz, f)) != 0)
  75.             crc = crc_calc(crc, buf, k);
  76.       fclose(f);
  77.       printf("%-14s %04X\n", fn, crc);
  78. }
  79.  
  80. #ifdef TEST
  81.  
  82. int main(int argc, char **argv)
  83. {
  84.       int i;
  85.  
  86.       if (argc < 2)
  87.       {
  88.             fprintf(stderr, "Usage: crc filename [filename...]\n");
  89.             return EXIT_FAILURE;
  90.       }
  91.       init_crc_table();
  92.       for (i = 1; i < argc; i++)
  93.             do_file(argv[i]);
  94.       return EXIT_SUCCESS;
  95. }
  96.  
  97. #endif /* TEST */
  98.